package com.itms.tool.utils;

import android.annotation.TargetApi;
import android.graphics.Bitmap;
import android.os.Build;
import android.support.v4.util.LruCache;

public class ImageCache {

	private int mMaxCacheSize;
	private LruCache<String, Bitmap> mBitmapCache;
	
	public ImageCache() {
		this(0.2f);
	}
	
	public ImageCache(float cacheSizeFactor) {
		mMaxCacheSize = (int) (Runtime.getRuntime().maxMemory() * cacheSizeFactor);
		mBitmapCache = new LruCache<String, Bitmap>(mMaxCacheSize) {
			@Override
			protected int sizeOf(String key, Bitmap value) {
				return ImageCache.this.sizeOf(value);
			}
		};
	}
	
	@TargetApi(Build.VERSION_CODES.HONEYCOMB_MR1)
	private int sizeOf(Bitmap bmp) {
		if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.HONEYCOMB_MR1) {
			return bmp.getByteCount();
		} else {
			return bmp.getRowBytes() * bmp.getHeight();
		}
	}
	
	public Bitmap get(String key) {
		return mBitmapCache.get(key);
	}
	
	public void put(String key, Bitmap bmp) {
		mBitmapCache.put(key, bmp);
	}
}
